package algorithm;

import java.util.ArrayList;
import java.util.List;

public class Leetcode22 {
    public List<String> generateParenthesis(int n) {

        List<String> list = new ArrayList<>();
        generateAll(new char[2*n], 0, list);
        return list;
    }

    public static void generateAll(char[] str, int pos, List<String> list) {
        if (pos == str.length) {
            if (valid(str)) {
                list.add(new String(str));
            }
            return;
        }

        str[pos] = '(';
        generateAll(str, pos+1, list);
        str[pos] = ')';
        generateAll(str, pos+1, list);

    }

    public static boolean valid(char[] str) {
        int balance = 0;
        for (int i = 0;i < str.length;i++) {
            if (str[i] == '(') {
                balance++;
            } else {
                balance--;
            }
            if (balance < 0) {
                return false;
            }
        }
        return balance == 0;
    }

    public List<String> generateParenthesis2(int n) {
        List<String> ans = new ArrayList<>();
        backtrack(ans, new StringBuilder(), 0, 0, n);
        return ans;
    }

    public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
        if (cur.length() == max * 2) {
            ans.add(cur.toString());
            return;
        }
        if (open < max) {
            cur.append('(');
            backtrack(ans, cur, open+1, close, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (close < open) {
            cur.append(')');
            backtrack(ans, cur, open, close+1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }

    public static void main(String[] args) {
        String str = "开屏广告-视频- Android";
        System.out.println(str.toLowerCase());
    }
}
